package com.yequan.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @author : Administrator
 * @date : 2020/2/12
 */
public class ActiveMqQueueConsumerDemo {

    public static void testQueueConsumer() {
        try {
            //1.创建一个连接器工厂对象connectionFactory
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.157.140:61616");
            //2.是用连接器工厂对象connectionFactory创建一个链接对象connection
            Connection connection = connectionFactory.createConnection();
            //3.开启连接
            connection.start();
            //4.使用connection对象创建session对象
            //第一个参数:是否开启事务.如果开启事务,则第二个参数无意义,一半不开启事务
            //第二个参数:应答模式.自动应答或手动应答,一般为自动应答
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //5.使用session对象创建destination对象
            Queue queue = session.createQueue("test-queue");
            //6.使用session对象创建consumer对象,指定destination
            MessageConsumer consumer = session.createConsumer(queue);
            //7.接收消息
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        String text = textMessage.getText();
                        System.out.println(text);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
            System.in.read();
            //8.关闭资源
            consumer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testQueueConsumer();
    }

}
